#!/usr/bin/env bash

set -euo pipefail

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log() {
  printf "%b[%s] %s%b\n" "${GREEN}" "$(date -u +"%Y-%m-%dT%H:%M:%SZ")" "$1" "${NC}"
}

warn() {
  printf "%b[%s] %s%b\n" "${YELLOW}" "$(date -u +"%Y-%m-%dT%H:%M:%SZ")" "$1" "${NC}"
}

error() {
  printf "%b[%s] %s%b\n" "${RED}" "$(date -u +"%Y-%m-%dT%H:%M:%SZ")" "$1" "${NC}" >&2
}

require_env() {
  local name="$1"
  if [[ -z "${!name:-}" ]]; then
    error "environment variable ${name} is required"
    exit 1
  fi
}

main() {
  require_env "PGHOST"
  require_env "PGUSER"
  require_env "PGDATABASE"
  : "${PGPORT:=5432}"
  : "${PGSSLMODE:=disable}"

  local schema_path="${SCHEMA_PATH:-/app/db/scheme.sql}"

  # Wait for database to be reachable
  echo "Waiting for PostgreSQL to be ready at ${PGHOST}:${PGPORT}..."
  until pg_isready --host="${PGHOST}" --port="${PGPORT}" --username="${PGUSER}" >/dev/null 2>&1; do
    sleep 2
  done

  if [[ ! -f "${schema_path}" ]]; then
    error "schema file not found: ${schema_path}"
    exit 1
  fi

  log "starting database initialization"
  log "target database: ${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}"

  local psql_args=(
    "--host=${PGHOST}"
    "--port=${PGPORT}"
    "--username=${PGUSER}"
    "--dbname=${PGDATABASE}"
    "--file=${schema_path}"
    "--echo-all"
  )

  export PGSSLMODE
  export PGPASSWORD="${PGPASSWORD:-}"

  warn "applying schema from ${schema_path}"
  psql "${psql_args[@]}" -v ON_ERROR_STOP=1

  log "database initialization completed successfully"
}

main "$@"

